package com.qianbao.qianbaobusiness.ui.help;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.androidbase.dagger.help.GlideApp;
import com.androidbase.dialog.LoadingDialog;
import com.androidbase.utils.DisplayUtils;
import com.androidbase.utils.ToastUtils;
import com.baseandroid.config.Global;
import com.baseandroid.mvp.BaseMvpActivity;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.help.PermissionDialogHelper;
import com.qianbao.qianbaobusiness.json.FeedBackTagBean;
import com.qianbao.qianbaobusiness.ui.widget.RouteeGridLayout;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

public class FeedBackActivity extends BaseMvpActivity<FeedBackView, FeedBackPresenter> implements FeedBackView, RouteeGridLayout.OnItemClickListener, View.OnClickListener {

    @BindView(R.id.tv_title)
    TextView         mTvTitle;
    @BindView(R.id.tv_right_click)
    TextView         mTvRightClick;
    @BindView(R.id.tv_head_title)
    TextView         mTvHeadTitle;
    @BindView(R.id.tv_notify)
    TextView         mTvNotify;
    @BindView(R.id.rgl_tag)
    RouteeGridLayout mRglTag;
    @BindView(R.id.et_feedback_content)
    EditText         mEtFeedbackContent;
    @BindView(R.id.tv_count)
    TextView         mTvCount;
    @BindView(R.id.tv_notify_img)
    TextView         mTvNotifyImg;
    @BindView(R.id.iv_feedback_image)
    ImageView        mIvFeedbackImage;
    @BindView(R.id.textView)
    TextView         mTextView;
    @BindView(R.id.ll_commit)
    LinearLayout     mLlCommit;
    @BindView(R.id.sv_feedback)
    ScrollView       mSvFeedback;
    @BindView(R.id.tv_done_info)
    TextView         mTvDoneInfo;
    @BindView(R.id.ll_commit_success)
    LinearLayout     mLlCommitSuccess;
    @BindView(R.id.iv_back_toolbar)
    ImageView        mIvBackToolbar;
    private String mSceneId;
    private String mDate;
    private String mMoney;
    private int                                                       mSelectedTagCount    = 0;
    private int                                                       mSuggestionTextCount = 0;
    private InputFilter                                               emojiFilter          = new InputFilter() {
        Pattern emoji = Pattern.compile(
                "[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            Matcher emojiMatcher = emoji.matcher(source);
            if (emojiMatcher.find()) {
                ToastUtils.showLongToast("不能输入表情");
                return "";
            }
            return null;
        }
    };
    private List<FeedBackTagBean.FeedbackTagSceneCfgBean.TagListBean> mTagList             = new ArrayList<>();
    private String        mTagListStr;
    private String        contentText;
    private LoadingDialog mLoadingDialog;
    private Dialog        mPopupDialog;
    private Button        mBtTakePhoto;
    private Button        mBtPickImg;
    private Button        mBtCancel;
    public static String FILEPATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
    public static String FILENAME = "tempPhotoPersonal";
    public static String SUFFIX   = ".png";
    private File   file;
    private String mFilePath;
    private String mFrontPath;
    private Uri    photoUri;
    private static final int REQUEST_CODE_IMAGE  = 1;
    private static final int REQUEST_CODE_CAMERA = 2;
    private Uri     imgUri;
    private boolean needUploadImg;
    private boolean isFromCamera;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_feedback;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void setupView() {
        mTvTitle.setText("问题反馈");
        mTvRightClick.setText("提交");
        mTvRightClick.setVisibility(View.VISIBLE);
        mTvRightClick.setEnabled(false);
        mTvRightClick.setTextColor(ContextCompat.getColor(this, R.color.text_support));
        initBundle();
        getPresenter().getFeedbackTags(mSceneId);
        mRglTag.setOnItemClickListener(this);
        mEtFeedbackContent.setFilters(new InputFilter[]{emojiFilter, new InputFilter.LengthFilter(300)});
        mEtFeedbackContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mTvCount.setText(s.length() + "/300");
                mSuggestionTextCount = s.length();
                if (mSuggestionTextCount == 0) {
                    mTvRightClick.setTextColor(ContextCompat.getColor(FeedBackActivity.this, R.color.text_support));
                    mTvRightClick.setEnabled(false);
                } else if (mSelectedTagCount > 0) {
                    mTvRightClick.setTextColor(ContextCompat.getColor(FeedBackActivity.this, R.color.text_red));
                    mTvRightClick.setEnabled(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        file = new File(FILEPATH + "/" + FILENAME + SUFFIX);
        mFilePath = Environment.getExternalStorageDirectory().getPath();
        mFrontPath = mFilePath + "/" + "front.png";
    }

    private void initBundle() {
        Bundle b = getIntent().getExtras();
        if (b != null) {
            mSceneId = b.getString("sceneId", "2");
            mDate = b.getString("date", "");
            mMoney = b.getString("money", "");
        }
        switch (mSceneId) {
            case "1":
                if (!TextUtils.isEmpty(mDate)) {
                    String titleString = "您对 " + mDate + " 金额 " + mMoney + " 的账单问题是";
                    SpannableString spannableString = new SpannableString(titleString);
                    ForegroundColorSpan colorSpan = new ForegroundColorSpan(ContextCompat.getColor(this, R.color.text_red));
                    spannableString.setSpan(colorSpan, 2, spannableString.length() - 6, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    mTvHeadTitle.setText(spannableString);
                } else {
                    mTvHeadTitle.setText("您反馈的问题是");
                }
                break;
            case "2":
                mTvHeadTitle.setText("您反馈的问题是");
                break;
            default:
                break;
        }
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {

    }

    @OnClick({R.id.iv_back_toolbar, R.id.tv_right_click, R.id.iv_feedback_image})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back_toolbar:
                finish();
                break;
            case R.id.tv_right_click:
                submit();
                break;
            case R.id.iv_feedback_image:
                RxPermissions rxPermissions = new RxPermissions(this);
                if (rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE) && rxPermissions.isGranted(Manifest.permission.CAMERA)) {
                    showChoosePickDialog();
                } else {
                    rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                            .subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean aBoolean) throws Exception {
                                    if (aBoolean) {
                                        showChoosePickDialog();
                                    } else {
                                        new PermissionDialogHelper(FeedBackActivity.this).setMsg("没有文件存储或相机权限，请去设置页添加相应权限").show();
                                    }
                                }
                            });
                }
                break;
            default:
                break;
        }
    }

    private void submit() {
        if (TextUtils.equals(mTvRightClick.getText().toString(), "完成")) {
            finish();
            return;
        }
        mTagListStr = "";
        if (mTagList.size() != 0) {
            for (int i = 0; i < mRglTag.getChildCount(); i++) {
                if (mRglTag.getChildAt(i).isSelected()) {
                    mTagListStr += mTagList.get(i).getTagId() + ",";
                }
            }
            if (TextUtils.isEmpty(mTagListStr)) {
                return;
            } else {
                mTagListStr = mTagListStr.substring(0, mTagListStr.lastIndexOf(","));
            }
        }
        contentText = mEtFeedbackContent.getText().toString();
        if (TextUtils.isEmpty(contentText)) {
            return;
        }
        if (needUploadImg) {
            getPresenter().uploadImg(uri2File(imgUri));
        } else {
            getPresenter().submit(mEtFeedbackContent.getText().toString(), "", mSceneId, mTagListStr, "", Global.getUserInfoBean().getUser().getUserNo());
        }
    }

    private File uri2File(Uri uri) {
        File file = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
        int actual_image_column_index = actualimagecursor
                                                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor
                                  .getString(actual_image_column_index);
        file = new File(img_path);
        return file;
    }

    private void showChoosePickDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_select, null);
        mPopupDialog = new Dialog(this, R.style.customDialogTheme);
        mPopupDialog.setContentView(view);
        Window dialogWindow = mPopupDialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialogWindow.setWindowAnimations(R.style.PopupWindowAnimation);
        lp.width = DisplayUtils.getWidth();
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dialogWindow.setAttributes(lp);
        mPopupDialog.show();
        mBtTakePhoto = (Button) view.findViewById(R.id.btn_take_photo);
        mBtTakePhoto.setOnClickListener(this);
        mBtPickImg = (Button) view.findViewById(R.id.btn_pick_photo);
        mBtPickImg.setOnClickListener(this);
        mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        mBtCancel.setOnClickListener(this);
    }

    private void startCamera() {
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(this, "com.qianbao.qianbaobusiness.fileprovider", new File(mFrontPath));
        } else {
            uri = Uri.fromFile(new File(mFrontPath));
        }
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        photoUri = Uri.fromFile(new File(mFrontPath));
        startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA);
    }

    @Override
    public void getFeedbackTagSuccess(FeedBackTagBean bean) {
        mTagList.clear();
        mTagList.addAll(bean.getFeedbackTagSceneCfg().getTagList());
        mRglTag.setItems(mTagList);
    }

    @Override
    public void uploadImgSuccess(String url, String name) {
        getPresenter().submit(mEtFeedbackContent.getText().toString(),
                url,
                mSceneId,
                mTagListStr,
                name,
                Global.getUserInfoBean().getUser().getUserNo()
        );
    }

    @Override
    public void submitSuccess() {
        mSvFeedback.setVisibility(View.GONE);
        mLlCommitSuccess.setVisibility(View.VISIBLE);
        switch (mSceneId) {
            case "1":
                mTvDoneInfo.setText("我们将在5个工作日内与您取得联系，请保持电话畅通。");
                break;
            case "2":
                mTvDoneInfo.setText("我们将在2个工作日内与您取得联系，请保持电话畅通。");
                break;
            default:
                break;
        }
        mIvBackToolbar.setVisibility(View.GONE);
        mTvRightClick.setText("完成");
        mTvRightClick.setTextColor(ContextCompat.getColor(this, R.color.text_support));
        mTvTitle.setText("提交成功");
    }

    @Override
    public void showLoadingDialog() {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog();
        }

        if (!mLoadingDialog.isVisible()) {
            mLoadingDialog.show(getSupportFragmentManager(), "loadingdialog");
        }
    }

    @Override
    public void closeLoadingDialog() {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismissAllowingStateLoss();
        }
    }

    @Override
    public void onItemClick(TextView view) {
        if (view.isSelected()) {
            view.setSelected(false);
            view.setTextColor(Color.parseColor("#4A4A4A"));
            if (--mSelectedTagCount == 0) {
                mTvRightClick.setTextColor(ContextCompat.getColor(this, R.color.text_support));
                mTvRightClick.setEnabled(false);
            }
        } else {
            view.setSelected(true);
            view.setTextColor(Color.parseColor("#FF5A5A"));
            if (++mSelectedTagCount > 0 && mSuggestionTextCount > 0) {
                mTvRightClick.setTextColor(ContextCompat.getColor(this, R.color.text_red));
                mTvRightClick.setEnabled(true);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_IMAGE && resultCode == RESULT_OK) {
            imgUri = data.getData();
            mPopupDialog.dismiss();
            needUploadImg = true;
            isFromCamera = false;
        }
        if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK) {
            mPopupDialog.dismiss();
            needUploadImg = true;
            isFromCamera = true;
        }
        if (needUploadImg) {
            if (isFromCamera) {
                GlideApp.with(this).load(photoUri).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(mIvFeedbackImage);
            } else {
                GlideApp.with(this).load(imgUri).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(mIvFeedbackImage);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_take_photo:
                startCamera();
                break;
            case R.id.btn_pick_photo:
                Intent imgIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(imgIntent, REQUEST_CODE_IMAGE);
                break;
            case R.id.btn_cancel:
                if (mPopupDialog != null && mPopupDialog.isShowing()) {
                    mPopupDialog.cancel();
                }
                break;
            default:
                break;
        }
    }
}
